import { writeToLakeFile } from "./xlsx.js";
import dayjs from "dayjs";
import { sum, tryFilePath } from "./util.js";
import path from "path";

function getTypeAmount(funds) {
  const typeAmount = [0, 0, 0, 0];
  funds.forEach((v) => {
    switch (v.type) {
      case "中央预算内投资":
        typeAmount[0] += v.amount;
        break;
      case "省预算内前期工作经费":
        typeAmount[1] += v.amount;
        break;
      case "省预算内基本建设投资":
        typeAmount[2] += v.amount;
        break;
      case "地方政府专项债券":
        typeAmount[3] += v.amount;
        break;
      default:
        break;
    }
  });

  return typeAmount;
}

const areaSort = ["江川区", "澄江市", "通海县"];

export function saveAs(filtered) {
  const d = [];
  filtered.forEach((item) => {
    item.funds.forEach((fund) => {
      d.push({
        ...item,
        fund,
      });
    });
  });

  filtered.sort((a, b) => {
    return areaSort.indexOf(a.area) - areaSort.indexOf(b.area);
  });

  d.sort((a, b) => {
    return dayjs(a.fund.doc.date).isBefore(dayjs(b.fund.doc.date)) ? -1 : 1;
  });

  const total = sum(d.map((item) => item.fund.amount));
  const totalCentral = sum(
    d.map((item) =>
      item.fund.type === "中央预算内投资" ? item.fund.amount : 0
    )
  );
  const totalQianqi = sum(
    d.map((item) =>
      item.fund.type === "省预算内前期工作经费" ? item.fund.amount : 0
    )
  );
  const totalJijian = sum(
    d.map((item) =>
      item.fund.type === "省预算内基本建设投资" ? item.fund.amount : 0
    )
  );

  const totalZhuanzhai = sum(
    d.map((item) =>
      item.fund.type === "地方政府专项债券" ? item.fund.amount : 0
    )
  );

  const sumaryStr = `合计（${filtered.length} 个项目）`;
  const rows = [
    [
      "",
      "",
      sumaryStr,
      "-",
      "-",
      sum(filtered.map((item) => item.investment)),
      totalCentral,
      totalQianqi,
      totalJijian,
      totalZhuanzhai,
      total,
      "-",
      "-",
      "-",
      "-",
    ],
  ];
  let i = 1
  for (const p of filtered) {
    const typeAmount = getTypeAmount(p.funds);
    rows.push([
      i,
      p.area,
      p.name,
      p.content,
      "",
      p.investment,
      ...typeAmount,
      sum(p.funds.map((fund) => fund.amount)),
      p.department,
      "-",
      p.funds.map((fund) => fund.name).join(","),
      p.tags,
    ]);
    i++
  }
  const tpl = path.join("template", "lake_template.xlsx");
  const target = path.join("dist", "三湖争取资金.xlsx");
  writeToLakeFile(tpl, tryFilePath(target), rows);
}
